package com.boxin.ims.modules.wechat.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.tmessage.MessageNode;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessage;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessageFactory;
import com.thinkgem.jeesite.common.utils.DateUtils;

/**
 * @author Administrator
 * @date 2014-9-2
 * @function <p> 模板消息工具类 </p>
 */
public class TemplateMessageUtils {
	
	
	
	
	public static DefaultHttpClient httpclient;
	
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
	}
	
	
	
	
	
	public static String sendTemplateMessage(String token,TemplateMessage templateMessage){
		String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
		
		
		String openId = templateMessage.getOpenId();
		String tid = templateMessage.getTemplateId();
		String topcolor = templateMessage.getTopcolor();
		String url = templateMessage.getUrl();
		
		
		
		StringBuffer message = new StringBuffer();
		message.append("{").append("\n");
		message.append("\"touser\":\""+openId+"\",").append("\n");;
		message.append("\"template_id\":\""+tid+"\",");
		message.append("\"url\":\""+url+"\",").append("\n");;
		message.append("\"topcolor\":\""+topcolor+"\",").append("\n");;
		
			message.append("\"data\":{").append("\n");;
			
			for(MessageNode var : templateMessage.getMessageNodeList()){
				message.append("\""+var.getName()+"\": {").append("\n");;
				message.append("\"value\":\""+var.getValue()+"\",").append("\n");;
				message.append("\"color\":\""+var.getColor()+"\"").append("\n");;
				message.append("},").append("\n");
			}
			
			
			int pos = message.lastIndexOf("},");
			message.replace(pos, pos+2, "}");
			message.append("\n");
			
			
		message.append("}").append("\n");
		message.append("}");
		
		System.out.println(message.toString());
		
		try {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod(postUrl);
			httpost.setEntity(new StringEntity(message.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return null;
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-2  下午5:17:00
	 * @function <p> 模板消息 </p>
	 * @param token
	 * @param params	kev-value:   openId->?  tid->?   url->?  topcolor->?
	 * @param vars
	 * @return
	 * @throws Exception
	 */

	public static String sendTemplateMessage(String token,Map<String,String>params,List<MessageNode> vars)  throws Exception  {
		
		String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
		
		
		String openId = params.get("openId");
		String tid = params.get("tid");
		String topcolor = params.get("topcolor");
		String url = params.get("url");
		
		
		
		StringBuffer message = new StringBuffer();
		message.append("{").append("\n");
		message.append("\"touser\":\""+openId+"\",").append("\n");;
		message.append("\"template_id\":\""+tid+"\",");
		message.append("\"url\":\""+url+"\",").append("\n");;
		message.append("\"topcolor\":\""+topcolor+"\",").append("\n");;
		
			message.append("\"data\":{").append("\n");;
			
			for(MessageNode var : vars){
				message.append("\""+var.getName()+"\": {").append("\n");;
				message.append("\"value\":\""+var.getValue()+"\",").append("\n");;
				message.append("\"color\":\""+var.getColor()+"\"").append("\n");;
				message.append("},").append("\n");
			}
			
			message.substring(0, message.length()-3);
			
			int pos = message.lastIndexOf("},");
			message.replace(pos, pos+2, "}");
			message.append("\n");
			
			
		message.append("}").append("\n");
		message.append("}");
		
		System.out.println(message.toString());
		
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(postUrl);
		httpost.setEntity(new StringEntity(message.toString(), "UTF-8"));//params  为post请求的
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		System.out.println(object.toString());
		
		return "";
		
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-2  下午5:54:29
	 * @function <p> 积分兑换提醒 </p>
	 * @param memberName
	 * @param openId
	 * @param score
	 */
	public static void scoreExchangeMessage(String token, String memberName,String openId,Integer score){
		String tid = "rUnwEEjnNlIF5eKgDKKLokZMetKPt1Z6OYSw7rirWNY";
		
		List<MessageNode> memberSignTempt = new ArrayList<MessageNode>();
		
		// first
		MessageNode var_first = new MessageNode();
		var_first.setName("first");
		var_first.setValue("");
		var_first.setColor("");
		memberSignTempt.add(var_first);
		
		MessageNode var_productType = new MessageNode();
		var_productType.setName("productType");
		var_productType.setValue("积分兑换");
		
		
		MessageNode var_name = new MessageNode();
		var_name.setName("name");
		var_name.setValue("积分兑换");
		
		
		MessageNode var_points = new MessageNode();
		var_points.setName("points");
		var_points.setValue(score +"");
		
		
		MessageNode var_date = new MessageNode();
		var_date.setName("date");
		var_date.setValue(DateUtils.formatDate(new Date(), "yyyy年MM月dd日 hh时mi分"));
		
		
		
		MessageNode var_remark = new MessageNode();
		
		var_remark.setName("remark");
		var_remark.setValue("");
		memberSignTempt.add(var_remark);
		
		
		Map<String,String> params = new HashMap<String,String>();
		params.put("tid", tid);
		params.put("openId", openId);
		params.put("url", "");
		params.put("topcolor", "");
		
		
		try {
			sendTemplateMessage(token, params, memberSignTempt);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-2  下午5:00:07
	 * @function <p>  </p>
	 * @param tid
	 * @param memberName
	 * @param openId
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static String sendTemplateServiceDeadTimeMsg(String tid,String memberName,String openId,String token)throws Exception{
		
		String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
		
		StringBuffer message = new StringBuffer();
		message.append("{").append("\n");
		message.append("\"touser\":\""+openId+"\",").append("\n");;
		message.append("\"template_id\":\""+tid+"\",");
		message.append("\"url\":\"http://weixin.qq.com/download\",").append("\n");;
		message.append("\"topcolor\":\"#FF0000\",").append("\n");;
		
			message.append("\"data\":{").append("\n");;
			message.append("\"first\": {").append("\n");;
			message.append("\"value\":\"您租用的电动车已到期\",").append("\n");;
			message.append("\"color\":\"#173177\"").append("\n");;
			message.append("},").append("\n");;
			
			//Date
			message.append("\"keyword1\":{").append("\n");;
			message.append("\"value\":\"06月07日 19时24分\",").append("\n");;
			message.append("\"color\":\"#173177\"").append("\n");;
			message.append("},").append("\n");;
			
			//CardNumber
			message.append("\"keyword2\":{").append("\n");;
			message.append("\"value\":\"0426\",").append("\n");;
			message.append("\"color\":\"#173177\"").append("\n");;
			message.append("},").append("\n");;
			
			
			//Type
			message.append("\"remark\":{").append("\n");;
			message.append("\"value\":\"\\n\\n您租车的电动车已到期，请即时结算，谢谢！\",").append("\n");;
			message.append("\"color\":\"#FF0000\"").append("\n");;
			message.append("}").append("\n");;
			
			
		message.append("}").append("\n");
		message.append("}");
		
		System.out.println(message.toString());
		
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(postUrl);
		httpost.setEntity(new StringEntity(message.toString(), "UTF-8"));//params  为post请求的
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		System.out.println(object.toString());
		
		
		
		return "";
	}
	
	
	
	
	
	
	
	
	public static void main(String[] args) {
		
		WeChat wechat = new WeChat();
		wechat.setId(1L);
		wechat.setAppId("wxea5c08a1f11ac7b7");
		wechat.setAppSecret("3678ec5dba17aef40333c6cd4c6de8b2");
	}
	
	
	

}
